<?php
namespace Common\Controller;
use Think\Controller;
require_cache(APP_PATH.'Common/aes/wxBizDataCrypt.php');
class CommonController extends Controller
{

    public $key = 'yuanyi';
    public $url = "http://oss.beikg.cn/";
    /**
     * 生成随机汉字
     * @param $num
     * @return string
     */
    public function getChar($num)  // $num为生成汉字的数量
    {
        $b = '';
        for ($i = 0; $i < $num; $i++) {
            // 使用chr()函数拼接双字节汉字，前一个chr()为高位字节，后一个为低位字节
            $a = chr(mt_rand(0xB0, 0xD0)) . chr(mt_rand(0xA1, 0xF0));
            // 转码
            $b .= iconv('GB2312', 'UTF-8', $a);
        }
        return $b;
    }

    /**
     * 随机二维数组
     * @param $list
     * @return array
     */
    public function shuffle_assoc($list) {
        if (!is_array($list)) return $list;

        $keys = array_keys($list);
        shuffle($keys);
        $random = array();
        foreach ($keys as $key)
            $random[$key] = $this->shuffle_assoc($list[$key]);
        return $random;
    }

    //打乱中文字符串
    public  function str_rev($str){
        //先判断参数是否为字符串，且为UTF8编码
        if(!is_string($str)||!mb_check_encoding($str,"utf-8")){
            die("输入的不是utf8类型的字符串");
        }

        //用mb_strlen函获取算utf8字符串的长度
        $length=mb_strlen($str,"utf-8");

        //声明一个数组备用
        $arr=array();

        //将字符串拆开放入数组
        for($i=0;$i<$length;$i++){
            $arr[$i]=mb_substr($str,$i,1,"utf-8");
        }
        //打乱数组
        shuffle($arr);
        //将数组中单个字符元素重新组合成字符串
        $str=implode("",$arr);

        return $str;
    }

    /**
     * post请求
     * @param $url
     * @param $postdata
     * @return mixed
     */
    public function getcomponent($url,$postdata){

        $ch = curl_init(); //用curl发送数据给api

        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        $response = curl_exec($ch);
        curl_close( $ch );
        $rest = json_decode($response,true);
        return $rest;
    }

    /**
     * get请求
     * @param $url
     * @return mixed
     */
    public function curlget($url){
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        $response = curl_exec($ch);
        curl_close( $ch );
        $rest = json_decode($response,true);
        return $rest;
    }

    /*
     * 返回数据 统一json
     * $data array 返回的数据
     * $msg string
     * $code int 返回码 200成功 100失败
     *       400 sesssion过期
     *       600需要微信认证 700需要手机绑定 或者手机重新登录
     *       401 参数错误
     * return json {'data':[]/string/{},code:200} 200成功
     * */
    public function returnData($data=array(),$msg='成功',$code=200){
        $arr=array(
            'data'=>$data,
            'msg'=>$msg,
            'code'=>$code
        );
        $str =json_encode($arr);
        echo $str;
        exit;
    }

    //获取当前域名
    public function getDomain(){
        $domain ="http://";
        if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
        {
            $domain ="https://";
        }
        elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
        {
            $domain ="https://";
        }
        elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
        {
            $domain ="https://";
        }

        return $domain.$_SERVER['HTTP_HOST'];
    }

    /**
     * 用来加密验证
     * @return string
     */
    public function verification(){

        $key = $this->key;
        $verification = md5(date('YmdHi',time()).$key);

        return $verification;
    }

    /*
    * desc 获取session_id
    * 添加session有效期
    * */
    public function getSessionId(){

        $session_id = session_id();

        session('expire',time());

        return $session_id;

    }
    /*
     * 检查session
     * 2小时过期
     * */
    public function checkSession(){

        $expire = session('expire');

        if(is_null($expire)) return;

        $now_time=time()-$expire;

        //
        if($now_time>7200){

            session_destroy();

            $this->returnData(array(),'',400);


        }

        session('expire',time());

    }

    /**
     * 更新token
     * @param $appid
     * @param $secret
     * @return mixed
     */
    public function updatetoken($appid,$secret){


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res = $this->curlget($url);

        $where['appid'] = $appid;
        $where['secret'] = $secret;
        $token =  M('access_token')->field('access_token')->where($where)->find();

        $data = array(
            'access_token'=>$res['access_token'],
            'expires_in'=>$res['expires_in'],
            'createtime'=>time(),
            'appid'=>$appid,
            'secret'=>$secret,
        );
        if ($token){
            M('access_token')->where($where)->save($data);
        }else{
            if ($res['access_token']){
                M('access_token')->data($data)->add();
            }
        }

        return $res['access_token'];

    }

    /**
     * 获取token
     * @param $appid
     * @param $secret
     * @return mixed
     */
    public function gettoken($appid,$secret){

        $where['appid'] = $appid;
        $where['secret'] = $secret;
        $token =  M('access_token')->field('access_token,expires_in,createtime')->where($where)->find();
        $access_token = $token['access_token'];
        if (time()-$token['createtime']>=$token['expires_in']){
            $access_token = $this->updatetoken($appid,$secret);
        }

        return $access_token;

    }

    /**
     * 发送模板消息
     */

    public function sendtemplate($appid,$secret,$data){

        $access_token = $this->gettoken($appid,$secret);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

        $res = $this->getcomponent($url,json_encode($data,true));

        return $res;

    }

    /**
     * 获取token2
     * @param $appid
     * @param $secret
     * @return mixed
     */
    public function gettoken2($appid,$secret){

        $name = $appid.'access_token';
        $access_token = S($name);

        if (!empty($access_token)){
            return $access_token;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res = $this->curlget($url);

        S($name,$res['access_token'],$res['expires_in']);

        return S($name);

    }

    /**
     * 发送模板消息（优化）
     */

    public function sendtemplate2($access_token,$data){

        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

        $res = $this->getcomponent($url,json_encode($data,true));

        return $res;

    }



    /**
     * 微信群id
     * @param $appid
     * @param $sessionkey
     * @param $encryptedData
     * @param $iv
     * @return string
     */

    public function getopenGId($appid,$sessionkey,$encryptedData,$iv){

        $data = "";
        $pc = new \aes\WXBizDataCrypt($appid, $sessionkey);
        $errCode=$pc->decryptData($encryptedData,$iv,$data);

        if ($errCode==0){
            $data = json_decode($data,true);
            return $data['openGId'];
        }
        return '-1';
    }

    public function getencryptedData($appid,$sessionkey,$encryptedData,$iv){

        $data = "";
        $pc = new \aes\WXBizDataCrypt($appid, $sessionkey);
        $errCode=$pc->decryptData($encryptedData,$iv,$data);

        if ($errCode==0){
            return json_decode($data,true);
        }
        return '-1';
    }

    /**
     * 概率
     */
    public function probability(){

        $proArr=array('a'=>25,'b'=>50,'c'=>25);

        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);             //抽取随机数
            if ($randNum <= $proCur) {
                $result = $key;                         //得出结果
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        $red_total = rand(5,66) / 100;
        switch ($result)
        {
            case 'a':
                $red_total = mt_rand(5,16) / 100;
                break;
            case 'b':
                $red_total = mt_rand(16,40) / 100;
                break;
            case 'c':
                $red_total = mt_rand(40,66) / 100;
                break;
        }

        return $red_total;

    }

    /**
     * 概率
     */
    public function probability2(){

        $proArr=array('a'=>20,'b'=>60,'c'=>20);

        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);             //抽取随机数
            if ($randNum <= $proCur) {
                $result = $key;                         //得出结果
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        $red_total = rand(8,35) / 100;
        switch ($result)
        {
            case 'a':
                $red_total = mt_rand(8,10) / 100;
                break;
            case 'b':
                $red_total = mt_rand(10,30) / 100;
                break;
            case 'c':
                $red_total = mt_rand(30,35) / 100;
                break;
        }

        return $red_total;

    }



    /**
     * 获取网络文件
     * @param $url
     * @param string $save_dir
     * @param string $filename
     * @param int $type
     * @return array
     */
    public function getImage($url,$save_dir='',$filename='',$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }
        if(trim($save_dir)==''){
            $save_dir='./';
        }
//        if(trim($filename)==''){//保存文件名
//            $ext=strrchr($url,'.');
//            if($ext!='.gif'&&$ext!='.jpg'){
//                return array('file_name'=>'','save_path'=>'','error'=>3);
//            }
//            $filename=time().$ext;
//        }
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='/';
        }
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        //获取远程文件所采用的方法
        if($type){
            $ch=curl_init();
            $timeout=5;
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        //$size=strlen($img);
        //文件大小
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        unset($img,$url);
        return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
    }


}